package com.jzo2o.health.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jzo2o.health.mapper.ReservationBatchSettingMapper;
import com.jzo2o.health.model.domain.ReservationSetting;
import com.jzo2o.health.model.excel.ReservationImportData;
import com.jzo2o.health.service.IReservationBatchSettingService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.util.List;
import java.util.stream.Collectors;

import static org.codehaus.groovy.runtime.DefaultGroovyMethods.collect;

@Service
public class ReservationBatchSettingServiceImpl extends ServiceImpl<ReservationBatchSettingMapper,ReservationSetting> implements IReservationBatchSettingService {
    @Resource
    private ReservationBatchSettingMapper reservationBatchSettingMapper;

    @Override
    public void doImport(List<ReservationImportData> reservationImportDataList) {
        //将excel数据转换为实体
        List<ReservationSetting> reservationSettingList = reservationImportDataList.stream().map(rs -> {
            ReservationSetting reservationSetting = new ReservationSetting();
            //如果获取到的rs日期比今天要早
            if (rs.getDate().isBefore(LocalDate.now())) {
                throw new RuntimeException("预约日期不能早于今天");
            } else {
                reservationSetting.setOrderDate(rs.getDate());
            }
            //如果预约人数大于0且同时小于999
            if (rs.getNumber() < 999 && rs.getNumber() > 0) {
                reservationSetting.setNumber(rs.getNumber());
            } else {
                throw new RuntimeException("预约人数不能小于1或大于999");
            }
            return reservationSetting;
        }).collect(Collectors.toList());

//        reservationBatchSettingMapper.insertBatch(reservationSettingList);
        //3.遍历集合，判断表格中的数据是否在数据库中存在,如果存在则进行修改操作，不存在则进行新增
        for (ReservationSetting reservationSetting : reservationSettingList) {
            Integer count = lambdaQuery().eq(ReservationSetting::getOrderDate, reservationSetting.getOrderDate()).count();
            if (count == 0) {
                //进行新增操作
                save(reservationSetting);
            } else {
                //不为空则修改
                lambdaUpdate().set(ReservationSetting::getNumber, reservationSetting.getNumber())
                        .eq(ReservationSetting::getOrderDate, reservationSetting.getOrderDate())
                        .update();
            }
        }
    }
}